package com.zbkj.crmeb.chant.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.crmeb.enums.MarkupRateTypeEnum;
import com.zbkj.crmeb.store.model.MarkupRate;
import com.zbkj.crmeb.store.service.MarkupRateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelProduct;
import com.zbkj.crmeb.chant.request.ChannelProductRequest;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.service.IChannelProductService;
import com.zbkj.crmeb.chant.service.ITianMaoExcelService;
import com.zbkj.crmeb.chant.vo.ChannelProductVo;
import com.zbkj.crmeb.enums.ChannelTypeEnum;
import com.zbkj.crmeb.export.vo.ChannelProductExcelVo;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductDescription;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductService;

import lombok.extern.slf4j.Slf4j;

/**
 * 天猫商品导出模板
 * @Description: 
 * @author daigb
 * @date 2021-02-01
 */
@Slf4j
@Service
public class TianMaoServiceExcelImpl implements ITianMaoExcelService {
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    IChannelProductService channelProductService;
    @Autowired
    StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Resource
    private StoreProductDao storeProductDao;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private MarkupRateService markupRateService;

    
    private Map<Integer, CategoryMatch> categoryMatchMap = new HashMap<Integer, CategoryMatch>();
    
    @Override
    public List<ChannelProductExcelVo> excelTianMao(ChannelProductRequest reqParam, Integer page) {
        log.info("--------------- 开始查询待导出天猫商品 ---------------");
        // 获取所有需要导出的渠道商品//获取渠道商户信息
        ChannelMerchant channelMerchant = null;
        if (null != reqParam.getChannelId()){
            channelMerchant = channelMerchantService.getById(reqParam.getChannelId());
            if (ObjectUtils.isNotEmpty(channelMerchant)){
                MarkupRate markupRate = markupRateService.getOne(Wrappers.<MarkupRate>lambdaQuery()
                        .eq(MarkupRate::getMerId, channelMerchant.getId())
                        .eq(MarkupRate ::getType, MarkupRateTypeEnum.PLAT_平台加价率.getType())
                        .last("LIMIT 1"));
                reqParam.setChannelMarkupRate(markupRate.getRatio());
            }
        }
        PageHelper.startPage(page, 1000);
        List<ChannelProductVo> channelProductList = storeProductDao.selectChannelProductList(reqParam);
        PageInfo<ChannelProductVo> pageInfo = PageInfo.of(channelProductList);
        
        /*List<ChannelProduct> channelProducts = channelProductService.list(Wrappers.<ChannelProduct>lambdaQuery()
                .ne(ChannelProduct :: getPushFlag, 0)
                .eq(ChannelProduct :: getChannelType, ChannelTypeEnum.TIANMAO.getCode())
                .eq(ChannelProduct :: getIsDel, false)
                );*/
        // 获取所有类目和天猫对照数据
        List<CategoryMatch> categoryMatchs = categoryMatchService.list();
        categoryMatchMap = categoryMatchs.stream().collect(Collectors.toMap(CategoryMatch::getCategoryId, Function.identity(), (v1,v2) -> v2));
        
        List<ChannelProductExcelVo> channelProductExcelVos = new ArrayList<ChannelProductExcelVo>();
        excelProductToTianMao(pageInfo.getList(), channelProductExcelVos, channelMerchant);
        return channelProductExcelVos;
    }
    
    /**
     * 构建导出商品对象
     * @Description:  
     * @author daigb 
     * @param 
     * @return void
     * @throws
     */
    private void excelProductToTianMao(List<ChannelProductVo> channelProductVos, List<ChannelProductExcelVo> channelProductExcelVos, ChannelMerchant channelMerchant) {
        if(CollectionUtils.isEmpty(channelProductVos)) {
            return;
        }
        log.info("--------------- 本次导出天猫商品总数为: {} 条---------------", channelProductVos.size());
        
        for(ChannelProductVo channelProductVo : channelProductVos) {
            try {
                String barCode = channelProductVo.getProductBarcode();
                /*if(StringUtil.isEmpty(barCode)) {
                    log.info("--------------- 渠道商品: {}, barCode为空 ---------------", channelProductVo.getId());
                    continue;
                }
                // 查询商品表
                StoreProduct storeProduct = storeProductService.getByBarCode(barCode);
                if(null == storeProduct) {
                    log.info("--------------- 渠道商品barCode: {}, 未查询到对应商品 ---------------", barCode);
                    continue;
                }
                if(!storeProduct.getIsShow()) {
                    log.info("--------------- 渠道商品barCode: {}, 该商品已下架, 不进行更新 ---------------", barCode);
                    continue;
                }*/
                Integer productId = channelProductVo.getProductId();
                // 查询sku表
                List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                    .eq(StoreProductAttrValue :: getProductId, productId)
                    );
                if(CollectionUtils.isEmpty(storeProductAttrValues)) {
                    log.info("--------------- 商品barCode: {}, 未查询到对应sku属性 ---------------", barCode);
                    continue;
                }
                // 查询商品描述
                StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                    .eq(StoreProductDescription :: getProductId, productId)
                    .last("LIMIT 1")
                    );
                if(null == storeProductDescription) {
                    log.info("--------------- 商品barCode: {}, 未查询到对应Description属性 ---------------", barCode);
                    continue;
                }
                
                // 构建对象
                buildTianmaoProduct(channelProductVo, storeProductAttrValues, storeProductDescription, channelProductExcelVos, channelMerchant);
            } catch (RestClientException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    /**
     * 构建天猫商品对象
     * @Description:  
     * @author daigb 
     * @param @return
     * @return JSONArray
     * @throws
     */
    private void buildTianmaoProduct(ChannelProductVo channelProductVo, List<StoreProductAttrValue> storeProductAttrValues, StoreProductDescription storeProductDescription, List<ChannelProductExcelVo> channelProductExcelVos, ChannelMerchant channelMerchant) {
        // 对照类目和类别
        CategoryMatch categoryMatch = categoryMatchMap.get(Integer.parseInt(channelProductVo.getCateId()));
        String category = "Shoes>Men\\\\'s>Fashion Sneakers";
        String productType = "shoes";
        String categoryName = "shoes";
        if(null != categoryMatch) {
            category = null == categoryMatch.getOthCategoryName() ? category : categoryMatch.getOthCategoryName();
            productType = null == categoryMatch.getOthCategoryType() ? productType : categoryMatch.getOthCategoryType();
            categoryName = null == categoryMatch.getCategoryName() ? categoryName : categoryMatch.getCategoryName();
        }
        // 颜色
        /*StringBuilder attrValueSb = new StringBuilder();
        for(int i=0; i<storeProductAttrValues.size(); i++) {
            attrValueSb.append(storeProductAttrValues.get(i).getSuk());
            attrValueSb.append(i == storeProductAttrValues.size()-1 ? "" : "/");
        }*/
        MarkupRate markupRate = markupRateService.getOne(Wrappers.<MarkupRate>lambdaQuery()
                        .eq(MarkupRate::getMerId, channelMerchant.getId())
                        .eq(MarkupRate ::getType, MarkupRateTypeEnum.PLAT_平台加价率.getType())
                        .last("LIMIT 1"));
        // 构建请求对象
        for(StoreProductAttrValue attrValue : storeProductAttrValues) {
            String[] sukArr = attrValue.getSuk().split(",");
            BigDecimal price = null;
            // 固定售价
            if("1".equals(channelProductVo.getMarkupType())) {
                price = channelProductVo.getProductPrice();
            // 费率计算
            } else {
                if(null == markupRate.getRatio()) {
                    price = attrValue.getPrice();
                    log.error("--------------- 商品: {}已设置使用费率计算但未设置费率, 取售价: {} ---------------", channelProductVo.getProductBarcode(), price);
                } else {
                    price = attrValue.getPrice().add(PriceUtil.calePrice(attrValue.getPrice(), markupRate.getRatio().multiply(new BigDecimal("0.01")).toString()));
                }
            }
            if(StringUtil.isEmpty(channelProductVo.getStoreInfo())) {
                continue;
            }
            
            // 要处理的供应商id暂时写死三家
            String[] keywords = null;
            if("1".equals(channelProductVo.getSuppliersId())) {
                String channelKeyword = channelProductVo.getKeyword().trim().replaceAll("\\s+"," ");
                keywords = channelKeyword.split(" ");
            } else if("37".equals(channelProductVo.getSuppliersId()) || "4".equals(channelProductVo.getSuppliersId()) || "136".equals(channelProductVo.getSuppliersId())) {
                keywords = channelProductVo.getKeyword().split("-");
            }
            
            ChannelProductExcelVo channelProductExcelVo = new ChannelProductExcelVo();
            channelProductExcelVo.setSku((null != keywords ? keywords[0] : channelProductVo.getKeyword()) + (null == sukArr || 2 > sukArr.length ? "" :  "-" + sukArr[1]));
            channelProductExcelVo.setParentId(null != keywords && 3 <= keywords.length ? keywords[0] + "-" + keywords[2] : channelProductVo.getKeyword());
            channelProductExcelVo.setModel(null != keywords ? keywords[0] : channelProductVo.getKeyword());
            channelProductExcelVo.setIndustry("clothing_shoes_jewelry");
            channelProductExcelVo.setProductName(channelProductVo.getBrandName() + " " + categoryName);
            channelProductExcelVo.setBrand(channelProductVo.getBrandName());
            channelProductExcelVo.setCategory(categoryName);
            channelProductExcelVo.setColor(storeProductAttrValues.get(0).getSuk().split(",")[0]);
            channelProductExcelVo.setDescription(storeProductDescription.getDescription());
            channelProductExcelVo.setMaterial(channelProductVo.getStoreInfo());
            channelProductExcelVo.setOrigin("IT");
            channelProductExcelVo.setProductType(categoryName);
            channelProductExcelVo.setSizeChartType("eur"); 
            channelProductExcelVo.setSizeType("eur"); 
            channelProductExcelVo.setProductImages(channelProductVo.getSliderImage());
            channelProductExcelVo.setVariation((null == sukArr || 2 > sukArr.length ? "" : sukArr[1]));
            channelProductExcelVo.setBarcode(channelProductVo.getProductBarcode().substring(4, channelProductVo.getProductBarcode().length()));
            channelProductExcelVo.setWeight("");
            channelProductExcelVo.setWeightUnit("");
            channelProductExcelVo.setPriceMsrp("");
            channelProductExcelVo.setPriceRetail(attrValue.getSourceCost()+"");
            channelProductExcelVo.setPriceCost(price.toString());
            channelProductExcelVo.setQuantity(attrValue.getStock().toString());
            channelProductExcelVo.setIsAlive("true");
            channelProductExcelVo.setShortDescription("");
            channelProductExcelVo.setSizeChartImageUrl("eur");
            channelProductExcelVo.setOtherBarcodes((Integer.parseInt(channelProductVo.getProductBarcode().substring(4, channelProductVo.getProductBarcode().length())) + 1) + "");
            channelProductExcelVo.setDimension("");
            channelProductExcelVo.setIsMainSku(channelProductVo.getKeyword());
            channelProductExcelVos.add(channelProductExcelVo);
        }
    }
    
}
